package com.zxh.blog.interceptor;

import com.zxh.blog.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

  /**
      * @projectName: LoginInterceptor
      * @Description: TODO后台登录控制器
      * @author zxh
      * @date 2019/2/14 14:49
      */
@Component
public class LoginInterceptor implements HandlerInterceptor {
   @Autowired
    private RedisService redisService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //Object obj = request.getSession().getAttribute(HaloConst.USER_SESSION_KEY);
        String token = (String) request.getAttribute("token");
        Boolean obj=redisService.existsKey(token);
        //如果user不为空则放行
        if (obj) {
            return true;
        }
        //否则拦截并跳转到登录
        response.sendRedirect("api/admin/login");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
